package com.damai.action.impl;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;

import com.citywithincity.api.entities.Customer;
import com.citywithincity.api.utils.AccessUtil;
import com.citywithincity.api.utils.ApiUtil;
import com.citywithincity.api.utils.SignUtil;
import com.citywithincity.crypt.CryptFactory;
import com.citywithincity.crypt.IDataCrypt;
import com.citywithincity.utils.JsonUtil;
import com.damai.action.BaseServiceAction;

public class TokenAction extends BaseServiceAction {
	public TokenAction(String key) {
		super(key);
	}

	private IDataCrypt crypt = CryptFactory.getDataCrypt();
	
	private static final String BASE64="base64";
	
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map<String, Object> json = null;
		try{
			json = JsonUtil.read(request.getInputStream());
		}catch(IOException e){
			
			response.getWriter().println(JsonUtil.ERROR_ACCESS_TOKEN);
			return;
			
		}
		String deviceID = (String) json.get("deviceID");
		if(!SignUtil.verify(json,deviceID)){
			response.getWriter().print(JsonUtil.ERROR_SIGN_JSON);
			return;
		}else{
			int time = (Integer)json.get(ApiUtil.time);
			if(time < 0){
				time = -time;
			}
			int start=16-time%16;
			Customer customer = new Customer();
			String content = JsonUtil.success(AccessUtil.createToken(request,deviceID,time,null,customer));
			String key = deviceID.substring(start,start+16);
			try{
				byte[] bytes = crypt.encript(content.getBytes("UTF-8"),key.getBytes());
				String mode = request.getHeader("mode");
				if(BASE64.equals(mode)){
					response.getWriter().write(Base64.encodeBase64String(bytes));
				}else{
					response.getOutputStream().write(bytes);
				}
			}catch(Exception e){
				response.getWriter().write(JsonUtil.alert("数据解密失败,请稍后重试"));
			}
			
		}
		
		
	}

	
}
